package com.sunjob.mrosystem.logrecorder;

import cn.dev33.satoken.stp.StpUtil;
import com.sunjob.common.domain.system.SysBusinessLog;
import com.sunjob.common.domain.system.SysBusinessLogContent;
import com.sunjob.common.mroAnno.LogModuleType;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;

import java.time.Duration;
import java.time.LocalDateTime;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : Wangzurong
 * @create 2022-08-02 8:51
 * 业务日志记录类
 */
@Data
public class LogRecorder {
    private KafkaTemplate<String,Object> kafkaTemplate;
    private SysBusinessLog sysBusinessLog;
    private LocalDateTime start;

    public LogRecorder() {
        this.sysBusinessLog = new SysBusinessLog();
    }

    public void start(LogModuleType logModuleType) {
        // 记录日志模块
        this.sysBusinessLog.setBusinessLogModule(logModuleType);
        // 记录日志开始时间
        this.start = LocalDateTime.now();
        this.sysBusinessLog.setBusinessLogUserId(recordUserId());

}

    public void stop(SysBusinessLog.BusinessStatus businessStatus,SysBusinessLogContent content) {
        // 记录业务状态
        this.sysBusinessLog.setBusinessLogStatus(businessStatus);
        // 记录业务内容
        this.sysBusinessLog.setBusinessLogContent(content);
        // 记录业务耗时
        this.sysBusinessLog.setBusinessLogCost(Duration.between(start,LocalDateTime.now()).toMillis());
        // 记录业务创建时间
        this.sysBusinessLog.setBusinessLogTime(start);
        sendBusinessLog();
    }

    private Long recordUserId() {
       String userId = null;
        try {
            userId = (String) StpUtil.getLoginId();
        } catch (Exception e) {
           // 未登录
        }
        if(userId==null){
            return null;
        }
        return Long.valueOf(userId);
    }
    private void sendBusinessLog(){
        kafkaTemplate.send("businessLog",this.sysBusinessLog);
    }
}
